package service;

import model.Account;
import util.DBUtil;

import java.sql.*;
import java.util.Scanner;

public class TransactionService {
    private AccountService accountService;

    public TransactionService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            System.out.println("存款金额必须大于0！");
            return;
        }
        Account acc = accountService.getCurrentAccount();
        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);

            String updateSql = "UPDATE ly_accounts SET balance = balance + ? WHERE account_number=?";
            PreparedStatement ps = conn.prepareStatement(updateSql);
            ps.setDouble(1, amount);
            ps.setString(2, acc.getAccountNumber());
            ps.executeUpdate();

            String insertSql = "INSERT INTO ly_transactions(account_number,type,amount) VALUES(?,?,?)";
            ps = conn.prepareStatement(insertSql);
            ps.setString(1, acc.getAccountNumber());
            ps.setString(2, "存款");
            ps.setDouble(3, amount);
            ps.executeUpdate();

            conn.commit();
            acc.setBalance(acc.getBalance() + amount);
            System.out.println("存款成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void withdraw(double amount) {
        Account acc = accountService.getCurrentAccount();
        if (amount <= 0 || amount > acc.getBalance()) {
            System.out.println("取款金额非法或余额不足！");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);

            String updateSql = "UPDATE ly_accounts SET balance = balance - ? WHERE account_number=?";
            PreparedStatement ps = conn.prepareStatement(updateSql);
            ps.setDouble(1, amount);
            ps.setString(2, acc.getAccountNumber());
            ps.executeUpdate();

            String insertSql = "INSERT INTO ly_transactions(account_number,type,amount) VALUES(?,?,?)";
            ps = conn.prepareStatement(insertSql);
            ps.setString(1, acc.getAccountNumber());
            ps.setString(2, "取款");
            ps.setDouble(3, amount);
            ps.executeUpdate();

            conn.commit();
            acc.setBalance(acc.getBalance() - amount);
            System.out.println("取款成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void transfer(String toAccount, double amount) {
        Account fromAcc = accountService.getCurrentAccount();
        if (toAccount.equals(fromAcc.getAccountNumber())) {
            System.out.println("不能向自己转账！");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);

            PreparedStatement ps = conn.prepareStatement("SELECT * FROM ly_accounts WHERE account_number=?");
            ps.setString(1, toAccount);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                System.out.println("目标账户不存在！");
                return;
            }

            if (amount <= 0 || amount > fromAcc.getBalance()) {
                System.out.println("金额非法或余额不足！");
                return;
            }

            // 扣款
            ps = conn.prepareStatement("UPDATE ly_accounts SET balance = balance - ? WHERE account_number=?");
            ps.setDouble(1, amount);
            ps.setString(2, fromAcc.getAccountNumber());
            ps.executeUpdate();

            // 收款
            ps = conn.prepareStatement("UPDATE ly_accounts SET balance = balance + ? WHERE account_number=?");
            ps.setDouble(1, amount);
            ps.setString(2, toAccount);
            ps.executeUpdate();

            // 添加两条交易记录
            ps = conn.prepareStatement("INSERT INTO ly_transactions(account_number,type,amount) VALUES(?,?,?)");
            ps.setString(1, fromAcc.getAccountNumber());
            ps.setString(2, "转账支出");
            ps.setDouble(3, amount);
            ps.executeUpdate();

            ps.setString(1, toAccount);
            ps.setString(2, "转账收入");
            ps.setDouble(3, amount);
            ps.executeUpdate();

            conn.commit();
            fromAcc.setBalance(fromAcc.getBalance() - amount);
            System.out.println("转账成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryBalance() {
        Account acc = accountService.getCurrentAccount();
        if (acc != null) {
            System.out.printf("账户余额：%.2f\n", acc.getBalance());
        }
    }
    public void queryTransactions() {
        Account acc = accountService.getCurrentAccount();
        if (acc == null) {
            System.out.println("请先登录！");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM ly_transactions WHERE account_number = ? ORDER BY timestamp DESC LIMIT 10";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, acc.getAccountNumber());
            ResultSet rs = ps.executeQuery();

            System.out.println("最近交易记录：");
            while (rs.next()) {
                String type = rs.getString("type");
                double amount = rs.getDouble("amount");
                Timestamp ts = rs.getTimestamp("timestamp");
                System.out.printf("[%s] %s：%.2f 元\n", ts, type, amount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
